package com.test.connect;

import java.time.Duration;
import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.test.Constant;
import com.test.PropertiesInnerUtil;

import dev.miku.r2dbc.mysql.MySqlConnectionConfiguration;
import dev.miku.r2dbc.mysql.MySqlConnectionFactory;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactory;
import reactor.core.publisher.Mono;

public class GetDemo {
	private static Logger logger = LoggerFactory.getLogger(GetDemo.class);
	private static String userName = PropertiesInnerUtil.getString(Constant.DATASOURCE_LOCATION, "datasource.username");
	private static String password = PropertiesInnerUtil.getString(Constant.DATASOURCE_LOCATION, "datasource.password");

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch down = new CountDownLatch(1);
		MySqlConnectionConfiguration.Builder builder = MySqlConnectionConfiguration.builder()
	            .host("10.16.9.34")
	            .port(3306)
	            .connectTimeout(Duration.ofSeconds(3))
	            .username(userName)
	            .password(password)
	            .database("sms_crm_db");

		MySqlConnectionConfiguration configuration = builder.build();
		ConnectionFactory connectionFactory = MySqlConnectionFactory.from(configuration);
		Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

		long s = System.currentTimeMillis();
		connectionMono.flatMap(connection -> {
			logger.info("createStatement");
			return Mono.from(connection.createStatement("SELECT cid, logic_code, message_send_code, message_content FROM message_queue_receiver limit 10000").execute());
		})
		.flatMapMany(result -> {
			return result.map((row, metadata) -> row.get(1, Object.class));
		})
		.collectList()
		.subscribe(result -> {
			logger.info("spend time: " + (System.currentTimeMillis() - s));
			logger.info("subscribe: " + result.size());
			down.countDown();
		});
		down.await();
	}

}
